package com.example.demo.controller;

import com.example.demo.dto.ApiResponse;
import com.example.demo.request.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.example.demo.dto.ApiResponse;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 登录和注册逻辑合并
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<String>> handleUser(@RequestBody UserInfo loginRequest) {
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户名和密码不能为空"));
        }

        if (userService.userExists(username)) {
            // 用户已存在，执行登录操作
            if (userService.validatePassword(username, password)) {
                return ResponseEntity.ok(ApiResponse.success(null, "登录成功"));
            } else {
                return ResponseEntity.status(403).body(ApiResponse.error("密码错误"));
            }
        } else {
            // 用户不存在，执行注册操作
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername(username);
            userInfo.setPassword(password);
            userService.insertUser(userInfo);
            userService.saveUserInfo(loginRequest); // 注册时同时保存用户信息
            return ResponseEntity.ok(ApiResponse.success(null, "注册成功"));
        }
    }

    // 保存用户信息
    @PostMapping("/save")
    public ResponseEntity<ApiResponse<String>> saveUserInfo(@RequestBody UserInfo userInfo) {
        if (userInfo.getUsername() == null || userInfo.getUsername().isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户名不能为空"));
        }

        if (userService.userExists(userInfo.getUsername())) {
            // 更新用户信息
            userService.updateUserInfo(userInfo);
            return ResponseEntity.ok(ApiResponse.success(null, "用户信息更新成功"));
        } else {
            // 插入新用户信息
            userService.insertUser(userInfo);
            userService.saveUserInfo(userInfo);
            return ResponseEntity.ok(ApiResponse.success(null, "用户信息保存成功"));
        }
    }

    // 获取所有用户信息
    @GetMapping("/AllUser")
    public ResponseEntity<ApiResponse<List<UserInfo>>> getAllUsers() {
        List<UserInfo> allUsers = userService.getAllUsers(); // 获取所有用户信息
        if (allUsers.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.success(null, "没有用户信息"));
        }
        return ResponseEntity.ok(ApiResponse.success(allUsers, "获取用户信息成功"));
    }
}
